<script>
  import tree from '@/mixins/tree/index.js'
  import AjaxStore from '@/utils/store/proxyAjax'
  import store from './store'
  import { validateNumber } from '@/utils/validate'

	export default {
    name: 'sitetype',
    mixins: [tree, store],
	  data() {
	    return {
        catName: '',
        fullPath: '',
        // tree
        tree: {
          width: "280",
          accordion: false,
          isShowHeader: true,
          treeMenuButtonList: this.treeMenuBtns,
          treeOperateButtonList: this.treeOperateBtns,
          showCheckbox: false,
          selectTree: {},
          nextNodeKey: 'node',
          idKey: 'catId',
          search: {
            searchKey: 'nodeName'
          },
          title: '站点分类树',
          getNextChildNode: this.getNextNode,
          delNode: this.delNode
        },

        pidKey: 'pid',
        idKey: 'catId',
        labelKey: 'catName',
        nodeCheckedKey: 'checked',
        nodeChildrenKey: 'children',
        nodeLeafKey: "leaf",
        nodeIdKey: 'id',
        nodeLabelKey: 'text',

	      currentNode: null,
	      panelType: '',

	      addNodeInfoUrl: '/v1/sys/projectcategory/add',
	      updateNodeInfoUrl: '/v1/sys/projectcategory/update',
	      getNextNodeUrl: '/v1/sys/projectcategory/findNextChildNodeTree',
	      delNodeUrl: '/v1/sys/projectcategory/deleteNode',
	      getNodeInfoUrl: '/v1/sys/projectcategory/findById',
	      store: new AjaxStore({
	        url: '/v1/sys/projectcategory/query'
        }),

        formPanel: {
          add: {
            model: {
              "catId": "",
              "pid": "",
              "catName": "",
              "orderNo": "",
              "creator": "",
              "createdTime": "",
              "updator": "",
              "updatedTime": "",
              "remark": "",
              "fullPath": ""
            },
            fields: [
              { label: '父节点', prop: 'pid', placeholder: '请选择父节点', anchor: 24,  xType: 'SelectTree.TREE', ref: 'addCat', relatedFields:['addCatPath'],
                treeParams: {
                  get: {
                    url: '/v1/sys/projectcategory/findNextChildNodeTree',
                    nextNodeKey: 'node',
                    idKey: 'id'
                  }
                },
                valueToLabelParams: {
                  url: '/v1/sys/projectcategory/findNameById',
                  idKey: 'catId'
                },
                on: {
                  'visible-change': val => val && this.$refs.addForm.$refs.addCat.reload()
                }
              },
              { label: '分类名称', prop: 'catName', placeholder: '输入分类名称', anchor: 24,
                on: {
                  input: (val) => {
                    this.catName = val
                    if (!this.formPanel.add.model.pid) {
                      this.formPanel.add.model.fullPath = this.filterArray([this.catName]).join('/')
                    } else {
                      const selectGroupLabel = this.$refs.addForm.$refs.addCat.selectedLabel
                      this.formPanel.add.model.fullPath = this.filterArray([this.getFrontStr(this.fullPath, selectGroupLabel), this.catName]).join('/')
                    }
                  }
                }
              },
              { label: '备注', prop: 'remark', placeholder: '输入备注', anchor: 24, type: 'textarea'},
              { label: '全路径', prop: 'fullPath', anchor: 24, readonly: true, style: 'border: 0;', ref: 'addCatPath',
                on: {
                  'el.form.update': (val, ctx, origin, form) => {// 值,当前组件,关联组件
                    if (form.model.pid) {
                      this.getNodeInfo({catId: form.model.pid}).then(({ success, data }) => {
                        if ( success && data.fullPath) {
                          // 获取上级机构全路径
                          this.fullPath = data.fullPath
                          this.formPanel.add.model.fullPath = this.filterArray([this.getFrontStr(this.fullPath, origin.selectedLabel), form.model.catName]).join('/')
                        }
                      })
                    } else {
                      form.model.fullPath = this.filterArray([form.model.catName]).join('/')
                    }
                  }
                }
              }
            ],
            rules: {
              "catName": [{ required: true, message: '分类名称', trigger: 'blur' }]
            },
            title: '新增站点分类',
            type: 'ADD',
            ref: 'addForm',
            submitBtnList: this.addBtns
          },
          edit: {
            model: {
              "catId": "",
              "pid": "",
              "catName": "",
              "orderNo": "",
              "creator": "",
              "createdTime": "",
              "updator": "",
              "updatedTime": "",
              "remark": "",
              "fullPath": ""
            },
            fields: [
              { label: '父节点', prop: 'pid', placeholder: '请选择父节点', anchor: 24,  xType: 'SelectTree.TREE', ref: 'editCat', relatedFields:['editCatPath'],
                treeParams: {
                  get: {
                    url: '/v1/sys/projectcategory/findNextChildNodeTree',
                    nextNodeKey: 'node',
                    idKey: 'id'
                  }
                },
                valueToLabelParams: {
                  url: '/v1/sys/projectcategory/findNameById',
                  idKey: 'catId'
                },
                on: {
                  'update': (val, vnode, form)=>{
                    const selfId = this.editCat
                    const $tree = vnode.$refs.tree
                    const path = $tree.getNodePath(val) || []
                    for(let i = 0, len = path.length; i<len; i++){
                      if(selfId === path[i]['id']){
                        form.model.pid = ''
                        this.$message({
                          type: 'error',
                          message: '不能选择自身或自己的子节点作为父节点！'
                        })
                        break
                      }
                    }
                  },
                  'visible-change': val => val && this.$refs.editForm.$refs.editCat.reload()
                }
              },
              { label: '分类名称', prop: 'catName', placeholder: '输入分类名称', anchor: 24,
                on: {
                  input: (val) => {
                    this.catName = val
                    if (!this.formPanel.edit.model.pid) {
                      this.formPanel.edit.model.fullPath = this.filterArray([this.catName]).join('/')
                    } else {
                      const selectGroupLabel = this.$refs.editForm.$refs.editCat.selectedLabel
                      this.formPanel.edit.model.fullPath = this.filterArray([this.getFrontStr(this.fullPath, selectGroupLabel), this.catName]).join('/')
                    }
                  }
                }
              },
              { label: '备注', prop: 'remark', placeholder: '输入备注', anchor: 24, type: 'textarea'},
              { label: '全路径', prop: 'fullPath', anchor: 24, readonly: true, style: 'border: 0;', ref: 'editCatPath',
                on: {
                  'el.form.update': (val, ctx, origin, form) => {// 值,当前组件,关联组件
                    if (form.model.pid) {
                      this.getNodeInfo({catId: form.model.pid}).then(({ success, data }) => {
                        if ( success && data.fullPath) {
                          // 获取上级机构全路径
                          this.fullPath = data.fullPath
                          this.formPanel.edit.model.fullPath = this.filterArray([this.getFrontStr(this.fullPath, origin.selectedLabel), form.model.catName]).join('/')
                        }
                      })
                    } else {
                      form.model.fullPath = this.filterArray([form.model.catName]).join('/')
                    }
                  }
                }
              }
            ],
            rules: {
              "catName": [{ required: true, message: '分类名称', trigger: 'blur' }]
            },
            title: '编辑站点分类',
            type: 'EDIT',
            ref: 'editForm',
            submitBtnList: this.editBtns
          }
        }
      }
    },
    methods: {
      handleFormAdd() {
        return this.$refs.addForm.validate()
          .then(() => {
            return this.addNodeInfo(this.formPanel.add.model)
          })
          .then(({ success, message }) => {
            this.$message({
              type: success ? 'success' : 'error',
              message: success ? '添加项目站点分类成功！' : '添加项目站点分类失败！'
            })
            if (success) {
              this.addLocalTree(this.formPanel.add.model)
            } else {
              throw new Error('添加项目站点分类失败！')
            }
          })
          .catch(err => {
            console.log(err)
            return Promise.reject(err)
          })
      },
      handleFormEdit() {
        return this.$refs.editForm.validate()
          .then(() => {
            const params = { }
            Object.assign(params, this.formPanel.edit.model)
            if (!this.formPanel.edit.model.pid) {
              delete params.pid
            }
            return this.updateNodeInfo(params)
            // return this.updateNodeInfo(this.formPanel.edit.model)
          })
          .then(({ success, message }) => {
            this.$message({
              type: success ? 'success' : 'error',
              message: success ? '修改项目站点分类成功！' : '修改项目站点分类失败！'
            })
            if (success) {
              this.editLocalTree(this.formPanel.edit.model)
            } else {
              throw new Error('修改项目站点分类失败！')
            }
          })
          .catch(err => {
            console.log(err)
            return Promise.reject(err)
          })
      },
      getFrontStr(str, reg) {
        return str.split(reg)[0] + reg
      }
    },
    beforeCreate() {
      // 根据页面路由找出有权限访问的 url 数组
      const urlArr = (this.$route.meta && this.$route.meta.children || []).map(item => item.url)

      // 根据权限 url 数组过滤出能够使用的 按钮数组
      this.addBtns = [
        { label: '保存', methods: 'handleFormAdd', url: '/v1/sys/projectcategory/add', icon: 'el-icon-circle-check-outline', type: 'primary', disabled: false }
      ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url)

      this.editBtns= [
        { label: '保存', methods: 'handleFormEdit', url: '/v1/sys/projectcategory/update', icon: 'el-icon-circle-check-outline', type: 'primary', disabled: false }
      ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url)

      this.treeMenuBtns = [
        { label: '新增', methods: 'handleMenuAdd', url: '/v1/sys/projectcategory/add', icon: 'el-icon-circle-plus-outline', type: 'text', action: 'plus' },
        { label: '刷新', methods: 'refresh', url: '/v1/sys/projectcategory/findNextChildNodeTree', icon: 'el-icon-refresh', type: 'text' },
        { label: '展开', methods: 'expand', url: '/v1/sys/projectcategory/findNextChildNodeTree', icon: 'el-icon-rank', type: 'text' },
        { label: '折叠', methods: 'fold', url: '', icon: 'el-icon-arrow-up', type: 'text' }
      ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url)

      this.treeOperateBtns = (data) => {
        // 根据 systemType 帅选
        let btnList = []
        !data.systemType
          ? (btnList = [
            { type: 'text', url: '/v1/sys/projectcategory/add', icon: 'el-icon-plus', action: 'plus' },
            { type: 'text', url: '/v1/sys/projectcategory/deleteNode', icon: 'el-icon-delete', action: 'delete' },
          ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url))
          : (btnList = [
            { type: 'text', url: '/v1/sys/projectcategory/add', icon: 'el-icon-plus', action: 'plus' },
            { type: 'text', url: '/v1/sys/projectcategory/deleteNode', icon: 'el-icon-remove', action: 'delete' },
          ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url))
        return btnList
      }
    }
  }
</script>

<style lang="scss">
  .sitetype{
    .right{
      .submit-btn{
        display: flex;
        justify-content: flex-end;
      }
    }
  }
</style>
